import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/10/6 21:24
 */
public class MyArrayList {
    public int[] elem;
    public int useSize;
    public MyArrayList(){
        this.elem = new int[10];
    }
        // 打印顺序表
        public void display() {
            for (int i = 0; i < this.useSize; i++) {
                System.out.print(elem[i]+" ");
            }
            System.out.println();
        }
        // 在 pos 位置新增元素
        public void add(int pos, int data) {
        if(pos<0 || pos>useSize){
            System.out.println("位置不合法");
            return;
        }
        if(isFull()){
            Arrays.copyOf(this.elem,2*this.elem.length);//2倍扩容
        }
        //挪数据，往后挪直到遇到pos，再把要加的元素加入
            for (int i = this.useSize-1;i>=pos; i--) {
               this.elem[i+1] = this.elem[i];
            }
            this.elem[pos] = data;//加元素
            this.useSize++;
        }

    /**
     * 在加元素时，判断顺序表满不满，满了利用Array.copyOf()扩容
     * @return
     */
    public boolean isFull(){
        return this.useSize == this.elem.length;
        }

    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if(elem[i] == toFind){
                return true;
            }
        }
        return false;
    }
    // 查找某个元素对应的位置
    public int search(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if(elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }
    // 获取 pos 位置的元素
    public int getPos(int pos) {
        if(pos < 0 || pos >= useSize) return -1;
        if(isEmpty()){
            System.out.println("顺序表为空");
            return -1;
        }
         return elem[pos];
    }

    public boolean isEmpty(){
        return this.useSize == 0;
    }

    // 给 pos 位置的元素设为value
    public void setPos(int pos, int value) {
        if(pos<0 || pos>=useSize){
            System.out.println("位置不合法");
            return;
        }
        if(isEmpty()){
            System.out.println("顺序表为空");
            return ;
        }
        this.elem[pos]=value;
    }
    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        if(isEmpty()) return;
        int index = search(toRemove);
        if(index == -1){
            return;
        }
        for (int i = index; i < this.useSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.useSize--;
    }
    // 获取顺序表长度
    public int size() {
        return this.useSize;
    }
    // 清空顺序表
    public void clear() {
        this.useSize = 0;
        /**for (int i = 0; i < useSize; i++) {
            this.elem[i] = null;
        }
        this.useSize = 0;*/
    }
}
